﻿package com.webbei.myCustom.action;

import java.awt.Font;
import java.awt.FontMetrics;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

import javax.swing.JLabel;

import net.sf.json.JSONArray;

import org.apache.commons.io.FileUtils;
import org.apache.struts2.ServletActionContext;

import com.webbei.pojo.PicInfor;

public class MyUtil {

	public static void copy(String from, String to) {
		System.out.println("COPY:from:"+from+":to:"+to);
		String tofile=null;
		if(to.endsWith("/")){
			String filename = from.split("/")[from.split("/").length - 1];
			tofile = to + filename;
		}else{
			tofile=to;
		}
		if(!tofile.equals(from)){
			try {
				FileInputStream fis = new FileInputStream(from);
				FileOutputStream fos=new FileOutputStream(tofile);
				byte[] b = new byte[1024];
				int count;
				while ((count = fis.read(b, 0, b.length)) != -1) {
					fos.write(b, 0, count);
				}
				fis.close();
				fos.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	public static void delete(String filePath){
		File file=new File(filePath);
		if(file.isFile()&&file.exists()){
			file.delete();
		}
	}
	public static String format(String s){// ISO-8859-1 --> UTF-8
		try {
			if(s!=null&&!s.equals("")){
				s= new String(s.getBytes("ISO-8859-1"),"UTF-8");
			}
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return s;
	}

	public static String deformat(String s){// UTF-8 --> ISO-8859-1
		try {
			if(s!=null&&!s.equals("")){
				s= new String(s.getBytes("UTF-8"),"ISO-8859-1");
			}
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return s;
	}

	public static List<PicInfor> deserialize(String ss,String username,Integer type){//此处返回用于预览
		if(ss!=null){
		List<PicInfor> list = new ArrayList<PicInfor>();
		JSONArray ja = JSONArray.fromObject(ss);
		if(type==0){
			for(int i=0;i<ja.size();i++){
				PicInfor picinfor  =new PicInfor();
				String s=ja.getJSONObject(i).getString("picurl");
				String filefile=s.split("/")[s.split("/").length-1];
				picinfor.setPicUrl("img/resources/webbeiUserInfo/"+username+"/userCustom/"+filefile);
				picinfor.setWidth(Integer.valueOf(ja.getJSONObject(i).getString("width")));
				picinfor.setHeight(Integer.valueOf(ja.getJSONObject(i).getString("height")));
				picinfor.setLeft(Integer.valueOf(ja.getJSONObject(i).getString("left")));
				picinfor.setTop(Integer.valueOf(ja.getJSONObject(i).getString("top")));
				list.add(picinfor);
			}
		}else{
			for(int i=0;i<ja.size();i++){
				PicInfor picinfor  =new PicInfor();
				String s=ja.getJSONObject(i).getString("picurl");
				String filefile[]=s.split("/");
				picinfor.setPicUrl(filefile[filefile.length-2]+"/"+filefile[filefile.length-1]);
				picinfor.setWidth(Integer.valueOf(ja.getJSONObject(i).getString("width")));
				picinfor.setHeight(Integer.valueOf(ja.getJSONObject(i).getString("height")));
				picinfor.setLeft(Integer.valueOf(ja.getJSONObject(i).getString("left")));
				picinfor.setTop(Integer.valueOf(ja.getJSONObject(i).getString("top")));
				list.add(picinfor);
			}
		}

		return list;}else return null;
	}
	public static List<PicInfor> deserialize2(String ss){//此处返回temp目录的URL，是图片还没复制到个人文件夹，用于画出预览图片用的
		List<PicInfor> list = new ArrayList<PicInfor>();
		JSONArray ja = JSONArray.fromObject(ss);
		for(int i=0;i<ja.size();i++){
			PicInfor picinfor  =new PicInfor();
			System.out.println("deserialize2截取之前de图片："+ja.getJSONObject(i).getString("picurl"));
			String a[]=ja.getJSONObject(i).getString("picurl").split("/");
			int b=a.length;
			if(b>1){
				if(a[b-2].equals("userCustom")){
					//重定制的图片
					picinfor.setPicUrl("img/resources/webbeiUserInfo/"+a[b-3]+"/userCustom/"+a[b-1]);
				}else{
					//IMG下的图片(默认图标) / CarMark下的图片(品牌车标)
					picinfor.setPicUrl(a[b-2]+"/"+a[b-1]);
				}
			}
			picinfor.setWidth(Integer.valueOf(ja.getJSONObject(i).getString("width")));
			picinfor.setHeight(Integer.valueOf(ja.getJSONObject(i).getString("height")));
			picinfor.setLeft(Integer.valueOf(ja.getJSONObject(i).getString("left")));
			picinfor.setTop(Integer.valueOf(ja.getJSONObject(i).getString("top")));
			list.add(picinfor);
		}
		return list;
	}
	public static List<PicInfor> deserialize3(String ss){//输入有temp，输出就有temp
		List<PicInfor> list = new ArrayList<PicInfor>();
		String []string=ss.split("flag");
		for(int i=0;i<string.length;i++){
			String []str1=string[i].split("bz");
			PicInfor picinfor  =new PicInfor();
			picinfor.setPicUrl(str1[0]);
			picinfor.setWidth(Integer.parseInt(str1[4]));
			picinfor.setHeight(Integer.parseInt(str1[1]));
			picinfor.setLeft(Integer.parseInt(str1[2]));
			picinfor.setTop(Integer.parseInt(str1[3]));
			list.add(picinfor);
		}
		return list;
	}

	public static Map<String,Integer> getStrigWidthAndHeight(String strValue,Font font) {
		Map<String,Integer> map=new HashMap<String,Integer>();
		FontMetrics fm = new JLabel().getFontMetrics(font);
		String tmpChar = "";
		int chr_width = 0;
		int totalWidth = 0;
		int chr_height=0;
		int totalHeight=0;
		for (int i = 0,len=strValue.length(); i < len; i++) {
			tmpChar = strValue.substring(i, i + 1);
			chr_width = fm.stringWidth(tmpChar);
			chr_height=fm.getHeight();
			totalHeight=chr_height>totalHeight?chr_height:totalHeight;
            totalWidth += chr_width;
		}
		map.put("width", totalWidth);
		map.put("height", totalHeight);
		return map;
	}
	public static String standardization(String s){//格式化路径(去掉页面读取的路径的""和服务器地址)
		String result=s;
		char c=s.charAt(0);
		if(!((c>='a'&&c<='z')||(c>='A'&&c<='Z'))){//去掉双引号
			result=s.substring(1, s.length()-1);
		}
		String[] rs=result.split("/");
		if(!rs[0].equals("img")){//去掉服务器地址
			int l=rs.length;
			result=rs[l-4]+"/"+rs[l-3]+"/"+rs[l-2]+"/"+rs[l-1];
		}
		return result;
	}

	public static String uploadfile(File myfile,String myfileContentType,String savepath){//文件上传1
		/*文件,格式,保存位置(末尾不带/)——格式识别用fileContentType*/
		if(myfile==null) return null;
		String path = ServletActionContext.getServletContext().getRealPath("/")+savepath;
		String[] t = myfileContentType.split("/");
		String picname = String.valueOf((new Date().getTime()))+String.valueOf(new Random().nextInt(3)) + "."
				+ t[t.length - 1];
		if (myfile != null) {
			File savefile = new File(new File(path), picname);
			picname = savepath+"/" + picname;
			if (!savefile.getParentFile().exists())
				savefile.getParentFile().mkdirs();
			try {
				FileUtils.copyFile(myfile, savefile);
			} catch (IOException e) {
				return null;
			}
		}
		return picname;
	}
	public static String uploadfile1(File myfile,String filename,String savepath){//文件上传2
		/*文件,文件名,保存位置(末尾不带/)——格式识别用FileName的尾缀*/
		if(myfile==null) return null;
		String path = ServletActionContext.getServletContext().getRealPath("/")+savepath;
		String[] t = filename.split("\\.");
		String picname = String.valueOf((new Date().getTime()))
				+ String.valueOf(new Random().nextInt(3)) + "."
				+ t[t.length - 1];
		if (myfile != null) {
			File savefile = new File(new File(path), picname);
			picname = savepath+"/" + picname;
			if (!savefile.getParentFile().exists())
				savefile.getParentFile().mkdirs();
			try {
				FileUtils.copyFile(myfile, savefile);
			} catch (IOException e) {
				return null;
			}
		}
		return picname;
	}
	public static void deleteFiles(String string) {//删除一个文件夹下的所有文件(只限1级目录)
		System.out.println(string);
		File file = new File(string);
		if(!file.exists())file.mkdirs();
		File[] files = new File(string).listFiles();
		if(files!=null){
			for (int i = 0; i < files.length; i++) {
			    files[i].delete();
			}
		}
	}

	public static Long getId(){//获取一个16位的ID值（根据时间生成）
		String id_string=new SimpleDateFormat("yyMMddHHmmss").format(new Date()).toString()+String.format("%04d", (int)(Math.random()*9000+1000));
		System.out.println("返回的ID:"+id_string);
		return Long.parseLong(id_string);
	}
	public static void main(String[] args) {
		System.out.println(MyUtil.getStrigWidthAndHeight("iii",new Font("楷体",Font.PLAIN,12)));
	}
	public static String getChineseType(String format) {
		return format.replaceAll("[^\\u4e00-\\u9fa5]", "");
	}
}
